﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ServerSidePhysics.Core
{
    public static class Networking
    {
        public static void StartServer(int port = 8647)
        {
            StaticHelpers.Log(String.Format("Starting server on port {0} (default 8647)", port.ToString()));
            Globals.sListener = new System.Net.Sockets.TcpListener(IPAddress.Any, port);
            Globals.sListener.Start();
            StaticHelpers.Log("Server started (backlog = inf)");

            Thread t = new Thread(new ThreadStart(ConnectionAccepter));
            t.Start();
        }

        public static void ConnectionAccepter()
        {
            while(true)
            {
                StaticHelpers.Log("Waiting for client...");
                TcpClient client = Globals.sListener.AcceptTcpClient();
                StaticHelpers.Log(String.Format("Client {0} connected!, creating PhysicsClient object and starting SocketProcessor...", ((IPEndPoint)client.Client.RemoteEndPoint).Address));

                Physics.AddClient(new PhysicsClient(client));
            }
        }

        public static void ClearNetworking()
        {
            Globals.sListener.Stop();
            Globals.sListener = null;
        }
    }
}
